package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
   private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /*营业额统计*/
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        /*存放从begin到end每天的日期*/
        List<LocalDate>dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //把list转换为string 用逗号分割
        String liststr = StringUtils.join(dateList, ",");

        List<Double>turnoverlist=new ArrayList<>();
        for(LocalDate date:dateList){
            //每日的营业额：'已完成'的订单金额合计
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            //select sum(amount) from orders where order_time>beginTime and order_time<endTime and status=5
            Double turnover=orderMapper.sumByMap(map);
            if(turnover==null){
                turnover=0.0;
            }
            turnoverlist.add(turnover);
        }
        //把list转换为string 用逗号分割
        String turnliststr = StringUtils.join(turnoverlist, ",");
        TurnoverReportVO turnoverReportVO= TurnoverReportVO.builder()
                        .dateList(liststr)
                        .turnoverList(turnliststr)
                        .build();
        return turnoverReportVO;
    }
    /*用户统计 --用户总量 --新增用户量*/
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        /*存放从begin到end每天的日期*/
        List<LocalDate>dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //把list转换为string 用逗号分割
        String liststr = StringUtils.join(dateList, ",");
        //存放每天新增的用户数量select count(id) from user where create_time>beginTime and create_time<endTime
        List<Integer>newUserlist=new ArrayList<>();
        //存放每天总的用户数量select count(id) from user where create_time<endTime
        List<Integer> totalUserlist=new ArrayList<>();
        for(LocalDate date:dateList){
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("end",endTime);
            //总用户数量
            Integer totalUser=userMapper.countByMap(map);
            map.put("begin",beginTime);
            //新增用户数量
            Integer newUser=userMapper.countByMap(map);
            totalUserlist.add(totalUser);
            newUserlist.add(newUser);
        }
        UserReportVO userReportVO=UserReportVO.builder()
                .dateList(liststr)
                .totalUserList(StringUtils.join(totalUserlist,","))
                .newUserList(StringUtils.join(newUserlist,","))
                .build();
        return userReportVO;
    }
    /*订单统计*/
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        /*存放从begin到end每天的日期*/
        List<LocalDate>dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //把list转换为string 用逗号分割
        String liststr = StringUtils.join(dateList, ",");
         List<Integer>orderCountlist=new ArrayList<>();
          List<Integer>validorderCountlist=new ArrayList<>();
        for(LocalDate date:dateList){
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(date, LocalTime.MAX);
            //查询每天订单总数 select count(id) from orders where order_time>?and order_time<?
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            orderCountlist.add(orderCount);
            //查询每天有效订单总数 select count(id) from orders where order_time>?and order_time<? and status=5
            Integer validorderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            validorderCountlist.add(validorderCount);
        }
        //查询时间区间内的订单总数量
        Integer totalOrderCount = orderCountlist.stream().reduce(Integer::sum).get();
        //查询时间区间内的有效订单总数量
        Integer validOrderCount = validorderCountlist.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
        orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;}
        OrderReportVO orderReportVO=OrderReportVO.builder()
                .dateList(liststr)
                .orderCountList(StringUtils.join(orderCountlist, ","))
                .validOrderCountList(StringUtils.join(validorderCountlist, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }
   /*销量前十*/
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //订单status=5才行
        //select od.name,sum(od.number) from order_detail od,orders o where od.order_id=o.id and o.status=5 and o.order_time>? and order_time<? group by od.name order by number desc limit 0,10
       LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);
       LocalDateTime endTime=LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        //stream流的map 将list中的每个dto取出来 再得到其name 再将name用,拼接为string
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList=StringUtils.join(names, ",");
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList=StringUtils.join(numbers, ",");
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }
/*导出运营excel*/
    @Override
    public void exportBusinessDate(HttpServletResponse response) {
        //1.查询数据库 获取营业数据 --最近三十天
        LocalDate begin=LocalDate.now().minusDays(30);
        LocalDate end=LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO=workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),  LocalDateTime.of(end, LocalTime.MAX));
        //2.通过POI将数据写入excel文件
        //得到输入流
        InputStream in =this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel=new XSSFWorkbook(in);
            //往模板中填充数据
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end);
            //填充营业额
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            //订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //用户新增数
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            //有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //平均客单数
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
            XSSFRow row;
            //明细数据--一共30天
            for(int i=0;i<30;i++)
            {
                LocalDate date=begin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //3.通过输出流将excel文件下载到浏览器
             ServletOutputStream out = response.getOutputStream();
             excel.write(out);
             out.close();
             excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime,Integer status) {
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", status);
            return orderMapper.countByMap(map);
    }
}
